﻿using Furion;
using Furion.JsonSerialization;
using Furion.Logging.Extensions;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace iemtm.WeChat.Core.RabbitMQ
{
    public class RabbitMQHelper
    {
        public static string HostName = App.Configuration["RabbitMQ:HostName"];
        public static string UserName = App.Configuration["RabbitMQ:UserName"];
        public static string Password = App.Configuration["RabbitMQ:Password"];
        public static string PrefetchCount = App.Configuration["RabbitMQ:PrefetchCount"];


        public const string Lixise661RabbitmqExchange = "lixise.tc661.UpdateData";//交换机

        public static void Init()
        {
            Task.Run(() =>
            {
                StartUp_Consumer();
            });
        }
        /// <summary>
        /// 启动RabbitMQ消费者
        /// </summary>
        public static  void StartUp_Consumer()
        {
            IConnection _connection;
            IModel _model;
            _connection = new ConnectionFactory
            {
                HostName = HostName,
                UserName = UserName,
                Password = Password,
                AutomaticRecoveryEnabled = true
            }.CreateConnection();
            _model = _connection.CreateModel();
            _model.BasicQos(0, ushort.Parse(PrefetchCount), false);//公平分发、同一时间只处理50个消息。.
            #region 数据更新
            const string Lixise661RabbitMqQueue = "lixise.tc661.UpdateData.WebWxTest";//队列
            _model.ExchangeDeclare(Lixise661RabbitmqExchange, ExchangeType.Topic, true);
            _model.QueueDeclare(Lixise661RabbitMqQueue, true, false, false, null);
            _model.QueueBind(Lixise661RabbitMqQueue, Lixise661RabbitmqExchange, "", null);
            var Lixise661Consumer = new EventingBasicConsumer(_model);
            Lixise661Consumer.Received += (model, ea) =>
            {
                Task.Run(() =>
                {
                    try
                    {

                        string message = Encoding.UTF8.GetString(ea.Body);
                        RabbitModel info = JSON.GetJsonSerializer().Deserialize<RabbitModel>(message);
                        if (info.UpdateTime < DateTime.Now.AddMinutes(-7)) //7分钟之前的数据不更新 防止
                        {
                            return;
                        }
                        if (info.Type == RabbitTypeEnum.UpdateCG)
                        {
                            Collector enC = MemoryEntity.cBuffColl[info.DTUID];// CollectorList.Frist();


                            //Generator enG = null;
                            Generator enG = MemoryEntity.gBuffGen[info.DTUID];// GeneratorList.Frist(info.DTUID);


                            switch (info.UpdateType)
                            {
                                case RabbitUpdateTypeEnum.OnLine:
                                    {

                                        RabbitUpdateHelper.UpdateOnLine(enC, enG);


                                    }
                                    break;
                                case RabbitUpdateTypeEnum.OffLine:
                                    {
                                        RabbitUpdateHelper.UpdateOffLine(enC, enG);
                                    }
                                    break;
                                case RabbitUpdateTypeEnum.GPS:
                                    {
                                        RabbitUpdateHelper.UpdateGPS(JSON.GetJsonSerializer().Deserialize<UGPS>(info.obj.ToString()), enC, enG);
                                    }
                                    break;
                                case RabbitUpdateTypeEnum.RunState:
                                    {
                                        GenCollBaseAreaPrj gc = JSON.GetJsonSerializer().Deserialize<GenCollBaseAreaPrj>(info.obj.ToString());

                                        RabbitUpdateHelper.UpdateState(gc, enC, enG);
                                    }
                                    break;
                                case RabbitUpdateTypeEnum.RECORD:
                                    {
                                        GenCollBaseAreaPrj gc = JSON.GetJsonSerializer().Deserialize<GenCollBaseAreaPrj>(info.obj.ToString());

                                        RabbitUpdateHelper.UpdateRECORD(gc, enC, enG);
                                        //ThreadPool.QueueUserWorkItem(startStopState2Ann, enG);


                                    }
                                    break;
                                case RabbitUpdateTypeEnum.GENSTA:
                                    {
                                        GenCollBaseAreaPrj gc = JSON.GetJsonSerializer().Deserialize<GenCollBaseAreaPrj>(info.obj.ToString());

                                        RabbitUpdateHelper.UpdateGENSTA(gc, enC, enG);

                                    }
                                    break;
                                case RabbitUpdateTypeEnum.COMMON:
                                    {
                                        GenCollBaseAreaPrj gc = JSON.GetJsonSerializer().Deserialize<GenCollBaseAreaPrj>(info.obj.ToString());

                                        RabbitUpdateHelper.UpdateCOMMON(gc, enC, enG);

                                    }
                                    break;
                            }
                        }





                    }
                    catch (Exception e)
                    {
                        // CWorkEnvRef.env.LogWraper.WriteLogWithTime(string.Format("RabbitMQ ERROR:{0}", e.ToString()));
                       // Logger.Instance.WriteException(e, "RabbitMQ");
                        e.ToString().LogInformation("RabbitMQ");
                    }
                    finally
                    {
                        _model.BasicAck(ea.DeliveryTag, false);  //处理完成，手动确认
                    }
                });
            };
            _model.BasicConsume(Lixise661RabbitMqQueue, false, Lixise661Consumer);

            #endregion

        }
    }
}
